var DEFAULT_INTERVAL = 1000 / 60;

//初始化状态
var STATE_INITIAL = 0;
//开始状态
var STATE_START = 1;
//停止状态
var STATE_STOP = 2;

var requestAnimationFrame = (function() {
	return window.requestAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		function(callback) {
			return window.setTimeout(callback, callback.interval || DEFAULT_INTERVAL);
		}
})();

var cancelAnimationFrame = (function() {
	return window.cancelAnimationFrame ||
		window.webkitCancelAnimationFrame ||
		window.mozCancelAnimationFrame ||
		window.oCancelAnimationFrame ||
		function(id) {
			return window.clearTimeout(id);
		};
})();

/**
 * Timeline时间轴类
 */
function Timeline() {
	this.animationHandler = 0;
	this.state = STATE_INITIAL;
}

/**
 * 时间轴每次回调执行的函数
 * @param  time 从动画开始到当前执行时间
 */
Timeline.prototype.onenterframe = function(time) {

}

/**
 * 动画开始
 */
Timeline.prototype.start = function(interval) {
	if (this.state === STATE_START) {
		return;
	}
	this.state = STATE_START;
	this.interval = interval || DEFAULT_INTERVAL;
	startTimeline(this, +new Date());
}

/**
 * 动画停止
 */
Timeline.prototype.stop = function() {
	if (this.state != STATE_START) {
		return;
	}

	this.state = STATE_STOP;

	if (this.startTime) {
		this.duration = +new Date() - this.startTime;
	}
	cancelAnimationFrame(this.animationHandler);
}

/**
 * 动画重新开始
 */
Timeline.prototype.restart = function() {
	if(this.state == STATE_START){
		return;
	}
	if(!this.duration || !this.interval){
		return;
	}
	this.state = STATE_START;

	startTimeline(this, +new Date() - this.duration);
}

/**
 * 时间轴动画启动函数
 * @param  timeline 时间轴的实例
 * @param  startTime 动画开始时间戳
 */
function startTimeline(timeline, startTime) {
	timeline.startTime = startTime;
	nextTick.interval = timeline.interval;

	//记录上一次回调的时间
	var lastTick = +new Date();
	nextTick();

	/**
	 * 每一帧执行的函数
	 */
	function nextTick() {
		var now = +new Date();

		timeline.animationHandler = requestAnimationFrame(nextTick);

		if (now - lastTick >= timeline.interval) {
			timeline.onenterframe(now - startTime);
			lastTick = now;
		}
	}
}

module.exports = Timeline;